<template>
  <div></div>
  <baidu-map
      class="bm-view"
      :scroll-wheel-zoom="true"
      style="overflow: auto"
      :zoom="16"
      :center="{ lat: 38.818143, lng: 115.484621 }"
  >
    <bm-marker
        v-for="(site, index) in sitelist"
        :key="index"
        @click="address(site)"
        :title="site.sname"
        :position="{ lng: site.slongitude, lat: site.slatitude }"
    ></bm-marker>

    <bm-driving
        v-if="luxian"
        :start="lushuPoint.start"
        :end="lushuPoint.end"
        :auto-viewport="true"
        :policy="BMAP_DRIVING_POLICY_LEAST_DISTANCE"
        :panel="true"
    >
    </bm-driving>
  </baidu-map>
</template>
<script setup>
import {  ref, onMounted } from 'vue'
import {allSite} from "@/api/map/map";
import {BmDriving} from "vue-baidu-map-3x";

const sitelist = ref([])

// 获取位置
const getUserLocation = () => {
  return new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(
        (position) => {
          resolve({
            latitude: position.coords.latitude,
            longitude: position.coords.longitude,
          })
        },
        (error) => {
          reject(error)
        },
    )
  })
}
getUserLocation()
    .then((location) => {
      console.log('用户当前位置:', location)
    })
    .catch((error) => {
      console.error('Error getting user location:', error)
    })
// 将角度转换为弧度
const deg2rad = (deg) => deg * (Math.PI / 180)
// 计算距离
const haversineDistance = (lat1, lon1, lat2, lon2) => {
  const R = 6371 // 地球平均半径，单位为公里
  const dLat = deg2rad(lat2 - lat1)
  const dLon = deg2rad(lon2 - lon1)
  const a =
      Math.sin(dLat / 2) * Math.sin(dLat / 2) +
      Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2)
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
  const distance = R * c // 距离，单位为公里
  return distance
}

const lushuPoint = ref({
  start: {
    lng: 0,
    lat: 0,
  },
  end: {
    lng: 0,
    lat: 0,
  },
})

const luxian = ref(false)......
function address(res) {
  getUserLocation().then((location) => {
    console.log('用户当前位置:', location)
    lushuPoint.value.start.lng = location.longitude
    lushuPoint.value.start.lat = location.latitude

    lushuPoint.value.end.lng = res.slongitude
    lushuPoint.value.end.lat = res.slatitude
    luxian.value = true
    all()
  })
}
function all() {
  allSite().then((res) => {
    console.log(res)
    sitelist.value = res.data
    console.log(sitelist.value)
  })
}
onMounted(() => {
  all()
})
</script>

<style>
.bm-view {
  width: 100%;
  height: 300px;
}
</style>
